package ua.maxicash.util.criteria.handlers;

import java.sql.Date;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Junction;
import org.hibernate.criterion.Restrictions;
import ua.maxicash.util.Filter;
import ua.maxicash.util.criteria.RestrictionsWrapper;

public class WorkDateCriteriaHandler extends CriteriaHandler{

    private static final Logger logger = Logger.getLogger(WorkDateCriteriaHandler.class);

    private Filter filter;

    public WorkDateCriteriaHandler() {
    }

    public WorkDateCriteriaHandler(List<String> aliases) {
        super(aliases);
    }

    @Override
    public void setUp(Filter filter) {
        this.filter = filter;
    }

    @Override
    public DetachedCriteria handle(DetachedCriteria criteria, Junction junction) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        if (!aliases.contains("schedule")) {
            criteria.createAlias("schedule", "schedule");
            aliases.add("schedule");
        }

        try {
            junction.add(RestrictionsWrapper.getCriterion(filter.getOp(), "schedule.workDate", new Date(df.parse(filter.getData()).getTime())));
		} catch (ParseException e) {
			logger.error(e);
		}
        return criteria;
    }
}
